package patrol.mobile.com.mobilepatrol.activity.security.emergency;

import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.LayoutDirection;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.activity.VideoPlayActivity;
import patrol.mobile.com.mobilepatrol.activity.security.ConsTitles;
import patrol.mobile.com.mobilepatrol.adapter.GlideImageLoader;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.DictListBean;
import patrol.mobile.com.mobilepatrol.bean.OrgListBean;
import patrol.mobile.com.mobilepatrol.bean.SaveCheck2Bean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.manager.UserManager;
import patrol.mobile.com.mobilepatrol.picker.matisse.Matisse;
import patrol.mobile.com.mobilepatrol.picker.matisse.MimeType;
import patrol.mobile.com.mobilepatrol.picker.matisse.engine.GlideEngine;
import patrol.mobile.com.mobilepatrol.utils.CommonParamsHelper;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.Constants;
import patrol.mobile.com.mobilepatrol.utils.DateUtil;
import patrol.mobile.com.mobilepatrol.utils.FileUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.LuBanHelper;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;
import patrol.mobile.com.mobilepatrol.widget.MyRadioGroup;
import patrol.mobile.com.mobilepatrol.widget.MySpinner;
import patrol.mobile.com.mobilepatrol.widget.dialog.SelectDialog;

import static patrol.mobile.com.mobilepatrol.activity.security.emergency.EmergencySaveCheck2Activity.REQUEST_CODE_VSELECT;
import static patrol.mobile.com.mobilepatrol.utils.DateUtil.format1;
import static patrol.mobile.com.mobilepatrol.utils.FileUtil.getNetVideoBitmap;
import static patrol.mobile.com.mobilepatrol.utils.SPUtils.get;

/**
 * Created by fuzhen.li on 2018/9/18.
 */
public class EmergencySaveCheckAddActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener {


    @BindView(R.id.sp_orgname)
    MySpinner spOrgname;
    @BindView(R.id.tv_checkman)
    TextView tvCheckman;
    @BindView(R.id.tv_checkLeader)
    EditText tvCheckLeader;
    @BindView(R.id.tv_checkDate)
    TextView tvCheckDate;
    @BindView(R.id.tv_checkOrgName)
    TextView tvCheckOrgName;
    @BindView(R.id.sp_largeType)
    MySpinner spLargeType;
    @BindView(R.id.sp_small_type)
    MySpinner spSmallType;
    @BindView(R.id.tv_checkPlace)
    EditText tvCheckPlace;
    @BindView(R.id.tv_checkSite)
    EditText tvCheckSite;
    @BindView(R.id.tv_checkContent)
    EditText tvCheckContent;
    //    @BindView(R.id.rb_none)
//    RadioButton rbNone;
//    @BindView(R.id.rb_danger)
//    RadioButton rbDanger;
//    @BindView(R.id.rb_other_problem)
//    RadioButton rbOtherProblem;
    @BindView(R.id.rg_peo)
    MyRadioGroup rgPeo;
    @BindView(R.id.tv_rectifyEndDate)
    TextView tvRectifyEndDate;
    @BindView(R.id.tv_problemNum)
    EditText tvProblemNum;
    @BindView(R.id.tv_problemName)
    EditText tvProblemName;
    @BindView(R.id.sp_type)
    MySpinner spType;
    @BindView(R.id.sp_problemLevel)
    MySpinner spProblemLevel;
    @BindView(R.id.tv_problemSynopsis)
    EditText tvProblemSynopsis;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_save)
    TextView tvSave;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();


    private String checkLeader = "";
    private String checkOrgName = "";
    private String largeType = "";
    private String smallType = "";
    private String checkContent = "";
    private String problemGenre = "";
    private String problemLevel = "";
    private String existProblems = "";
    private String completedBy = "";
    private String problemType = "";
    private String rectifyById = "";
    private String reviewBy = "";
    private String reviewDate = "";
    private String auditName = "";

    private String tvRectifyBy;
    private String tvRectifyNum;
    private String tvYesRectify;
    private String tvDeadlineRectify;
    private String tvRectifyEndDate2;
    private String auditFlag = "";
    private List<String> largelist = new ArrayList<>();
    private List<String> smalllist = new ArrayList<>();
    private List<String> problemGenrelist = new ArrayList<>();
    private List<String> problemLevellist = new ArrayList<>();
    private List<String> problemTypelist = new ArrayList<>();
    private List<String> orgNameList = new ArrayList<>();
    private List<String> orgIdList = new ArrayList<>();
    private String videoPath = "";

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_emergency_save_check_add;
    }

    //    abkWorksCheck_problemType
    @Override
    public void setListener() {
        getDictList("abkWorksCheck_problemType");//问题分类
        getDictList("abkWorksCheck_largeType");//检查大类
        getDictList("abkWorksCheck_smallType");//检查小类
        getDictList("abkWorksCheck_problemGenre");//类别
        getDictList("abkWorksCheck_problemLevel");//隐患级别
        getOrg();
    }

    private void getDictList(final String dictType) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.DICT_LIST);
        HashMap<String, String> map = new HashMap<>();
        map.put("dictType", dictType);
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                JsonParser jp = new JsonParser();
                JsonObject jo = jp.parse(response).getAsJsonObject();
                JsonArray listArray = jo.getAsJsonArray("list");
                List<DictListBean> dictListBeanList = GsonUtil.jsonToList(listArray.toString(), DictListBean.class);
                if (dictType.equals("abkWorksCheck_largeType")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        largelist.add(dictListBeanList.get(i).getLabel());
                    }
                    largeType = largelist.get(0);
                    spLargeType.setmDatas(largelist, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            largeType = largelist.get(postion);
                        }
                    });
                } else if (dictType.equals("abkWorksCheck_smallType")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        smalllist.add(dictListBeanList.get(i).getLabel());
                    }
                    smallType = smalllist.get(0);
                    spSmallType.setmDatas(smalllist, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            smallType = smalllist.get(postion);
                        }
                    });
                } else if (dictType.equals("abkWorksCheck_problemGenre")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        problemGenrelist.add(dictListBeanList.get(i).getLabel());
                    }
                    problemType = problemGenrelist.get(0);
                    spType.setmDatas(problemGenrelist, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            problemType = problemGenrelist.get(postion);
                        }
                    });
                } else if (dictType.equals("abkWorksCheck_problemLevel")) {
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        problemLevellist.add(dictListBeanList.get(i).getLabel());
                    }
                    problemLevel = problemLevellist.get(0);
                    spProblemLevel.setmDatas(problemLevellist, new MySpinner.CallBack() {
                        @Override
                        public void onSelect(int postion) {
                            problemLevel = problemLevellist.get(postion);
                        }
                    });
                } else if (dictType.equals("abkWorksCheck_problemType")) {
                    problemGenre = dictListBeanList.get(0).getLabel();
                    for (int i = 0; i < dictListBeanList.size(); i++) {
                        problemTypelist.add(dictListBeanList.get(i).getLabel());
                        RadioButton radioButton = new RadioButton(EmergencySaveCheckAddActivity.this);
                        radioButton.setTextSize(CommonUtil.dip2px(EmergencySaveCheckAddActivity.this,5));
                        RadioGroup.LayoutParams lp = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
                        lp.setLayoutDirection(LayoutDirection.LTR);

                        //设置RadioButton边距 (int left, int top, int right, int bottom)
                        lp.setMargins(15, 0, 0, 0);
                        //设置文字
                        radioButton.setText(dictListBeanList.get(i).getLabel());
                        radioButton.setLayoutParams(lp);
                        //设置radioButton的点击事件
//                        radioButton.setOnClickListener(new View.OnClickListener() {
//                            @Override
//                            public void onClick(View v) {
//                                problemGenre = radioButton.getText().toString();
//                            }
//                        });
                        if (i == 0) {
                            radioButton.performClick();
                        }
                        //将radioButton添加到radioGroup中
                        rgPeo.addView(radioButton);

                    }

//                    rgPeo.check(0);
                    rgPeo.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(MyRadioGroup group, int checkedId) {
                            RadioButton tempButton = (RadioButton) findViewById(checkedId); // 通过RadioGroup的findViewById方法，找到ID为checkedID的RadioButton
                            problemGenre = tempButton.getText().toString();
                        }
                    });


                }


            }
        });
    }

    private void getOrg() {
        HashMap<String, String> hashMap = new HashMap();
        hashMap.put("objType", "分局,总局");
        hashMap.put("orgId", UserManager.getOrgNo());
        HttpSender sender = new HttpSender(this, baseUrl, Urls.getOrgList);
        sender.requestPost(hashMap, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(final String code, String response) {
                final OrgListBean orgListBean = new Gson().fromJson(response, OrgListBean.class);
                orgNameList = new ArrayList<>();
                for (OrgListBean.ListBean listBean : orgListBean.getList()) {
                    orgNameList.add(listBean.getOrgName());
                    orgIdList.add(listBean.getId());
                }

                if (orgNameList != null && orgNameList.size() > 0) {
                    spOrgname.getmText().setText(orgNameList.get(0));
                }

                spOrgname.setmDatas(orgNameList, new MySpinner.CallBack() {
                    @Override
                    public void onSelect(int postion) {
                    }
                });
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
//        tv_name.setText(UserManager.getUser((String) SPUtils.get(Constants.current_id, "")).ryname);
//        tv_name2.setText("当前账户 : "+ UserManager.getUserName());
//        tv_com.setText(UserManager.getUser((String) get(Constants.current_id,"")).bmname);
        Intent intent = getIntent();
        if (null != intent) {
            String id = intent.getStringExtra("id");
            if (!TextUtils.isEmpty(id)) {
                requestData(id);
            } else {
                tvCheckman.setText(UserManager.getryName());
                tvCheckDate.setText(DateUtil.getCurrentDate(format1));
                tvCheckOrgName.setText(UserManager.getUser((String) get(Constants.current_id, "")).bmname);
            }
        }

        tvCheckDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(EmergencySaveCheckAddActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvCheckDate.setText(DateUtil.convert2String(date, format1));
                    }
                }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                pvTime.show();
            }
        });
        tvRectifyEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //时间选择器
                TimePickerView pvTime = new TimePickerView.Builder(EmergencySaveCheckAddActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        tvRectifyEndDate.setText(DateUtil.convert2String(date, format1));
                    }
                }).setType(new boolean[]{true, true, true, true, true, true}).setLabel("年", "月", "日", "时", "分", "秒").build();
                pvTime.show();
            }
        });
        initImagePicker();
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, limitSize);
        adapter.setOnItemClickListener(this);
        recyclerView.setLayoutManager(new GridLayoutManager(this, limitSize));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);


    }

    @Override
    public void initTitle() {
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(EmergencySaveCheckAddActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText(ConsTitles.EMERGENCY_SAVE_CHECK_2);
    }

    @OnClick({R.id.tv_save})
    public void onTVClick(View v) {

        switch (v.getId()) {

            case R.id.tv_save:
                submit();
                break;

        }

    }

    private void requestData(String id) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_SAVE_CHECK_LIST);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {

                SaveCheck2Bean saveCheck2Bean = GsonUtil.GsonToBean(response, SaveCheck2Bean.class);
                tvCheckman.setText(saveCheck2Bean.getCheckLeader());
                spOrgname.setText(saveCheck2Bean.getOrgName());
                tvCheckLeader.setText(saveCheck2Bean.getCheckLeader());
                tvCheckDate.setText(saveCheck2Bean.getCheckDate());
                tvCheckOrgName.setText(saveCheck2Bean.getCheckOrgName());
                spLargeType.setText(saveCheck2Bean.getLargeType());
                spSmallType.setText(saveCheck2Bean.getSmallType());
                tvCheckPlace.setText(saveCheck2Bean.getCheckPlace());
                tvCheckSite.setText(saveCheck2Bean.getCheckSite());
                tvCheckContent.setText(saveCheck2Bean.getCheckContent());
                tvRectifyEndDate.setText(saveCheck2Bean.getRectifyEndDate());
                tvProblemNum.setText(saveCheck2Bean.getProblemNum());
                tvProblemName.setText(saveCheck2Bean.getProblemName());
//               if (saveCheck2Bean.getProblemGenre().equals(rgPeo.get))

                spProblemLevel.setText(saveCheck2Bean.getProblemLevel());
                tvProblemSynopsis.setText(saveCheck2Bean.getProblemSynopsis());

                checkLeader = saveCheck2Bean.getCheckLeader();
                checkOrgName = saveCheck2Bean.getCheckOrgName();
                largeType = (saveCheck2Bean.getLargeType());
                smallType = (saveCheck2Bean.getSmallType());
                checkContent = (saveCheck2Bean.getCheckContent());
                existProblems = saveCheck2Bean.getExistProblems();
                completedBy = saveCheck2Bean.getCompletedBy();
                problemType = saveCheck2Bean.getProblemType();
                rectifyById = saveCheck2Bean.getRectifyById();
                reviewBy = saveCheck2Bean.getReviewBy();
                reviewDate = saveCheck2Bean.getReviewDate();
                auditName = saveCheck2Bean.getAuditName();

                tvRectifyBy = saveCheck2Bean.getRectifyBy();
                tvRectifyNum = saveCheck2Bean.getRectifyNum();
                tvYesRectify = saveCheck2Bean.getYesRectify();
                tvDeadlineRectify = saveCheck2Bean.getDeadlineRectify();
                tvRectifyEndDate2 = saveCheck2Bean.getRectifyEndDate();
                auditFlag = saveCheck2Bean.getAuditFlag();

                List<DeviceDetailImgBean> deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(EmergencySaveCheckAddActivity.this);
                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");
                    if (deviceDetailImgBean.getFileType().equals("mp4")) {
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = getNetVideoBitmap(replace);
                        String imgUrl = FileUtil.saveImg2Gallery(EmergencySaveCheckAddActivity.this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                        imageItem.path = imgUrl;
                        imageItem.name = replace;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                    } else {
                        long currentTime = System.currentTimeMillis();
                        fileHelper.savePicture(currentTime + ".jpg", replace);
                        ImageItem imageItem = new ImageItem();
                        UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                        try {
                            String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                            imageItem.path = filePath;
                            imageItem.mimeType = "image";
                            selImageList.add(imageItem);
                            upImgInfoBean.setId(deviceDetailImgBean.getId());
                            upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                            upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                            upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
//                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
//                    String url = baseUrl + deviceDetailImgBean.getFilePath();
//                    String replace = url.replace("\\", "/");
//
//                    long currentTime = System.currentTimeMillis();
//                    fileHelper.savePicture(currentTime + ".jpg", replace);
//                    ImageItem imageItem = new ImageItem();
//                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
//                    try {
//                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
//                        imageItem.path = filePath;
////                        Glide.with(AdviceDetail2Activity.this).load(new File(filePath)).into(iv);
//                        selImageList.add(imageItem);
//                        imgOldUUIDs.add(deviceDetailImgBean.getId());
//                        upImgInfoBean.setId(deviceDetailImgBean.getId());
//                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
//                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
//                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
//                        oldImgInfo.add(upImgInfoBean);
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });


            }
        });
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                            //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(4);              //选中数量限制
        imagePicker.setMultiMode(false);                      //多选
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }


    private void submit() {
        final HttpSender sender = new HttpSender(this, baseUrl, Urls.EMERGENCY_SAVE_CHECK_UPLOAD);

        HashMap<String, String> idDateBmnameMap = CommonParamsHelper.getIdDateBmnameMap();

        HashMap<String, Object> map = new HashMap<>();
        map.putAll(idDateBmnameMap);
        map.put("orgName", spOrgname.getmText().getText().toString());
        map.put("checkLeader", tvCheckLeader.getText().toString());
        map.put("checkDate", tvCheckDate.getText().toString());
        map.put("checkOrgName", tvCheckOrgName.getText().toString());
        map.put("largeType", spLargeType.getmText().getText().toString());
        map.put("smallType", spSmallType.getmText().getText().toString());
        map.put("checkPlace", tvCheckPlace.getText().toString());
        map.put("checkSite", tvCheckSite.getText().toString());
        map.put("checkContent", tvCheckContent.getText().toString());
        map.put("rectifyDate", tvRectifyEndDate.getText().toString());
        map.put("problemNum", tvProblemNum.getText().toString());
        map.put("problemName", tvProblemName.getText().toString());
        map.put("problemGenre", problemGenre);
        map.put("problemLevel", problemLevel);

        map.put("problemSynopsis", tvProblemSynopsis.getText().toString());
        map.put("existProblems", existProblems);
        map.put("completedBy", completedBy);
        map.put("problemType", problemType);
        map.put("rectifyById", rectifyById);
        map.put("reviewBy", reviewBy);
        map.put("reviewDate", reviewDate);
        map.put("auditName", auditName);
        map.put("auditFlag", auditFlag);
        map.put("tvRectifyBy", tvRectifyBy);
        map.put("tvRectifyNum", tvRectifyNum);
        map.put("tvYesRectify", tvYesRectify);
        map.put("tvDeadlineRectify", tvDeadlineRectify);
        map.put("tvRectifyEndDate2", tvRectifyEndDate2);


        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("abkWorksCheck", GsonUtil.map2Json(map));


        List<ImageItem> images = adapter.getImages();
        List<UpImgInfoBean> upImgInfoBeanList = new ArrayList<>();
        for (int i = 0; i < images.size() - oldImgInfo.size(); i++) {
            UpImgInfoBean imgInfoBean = new UpImgInfoBean();
            imgInfoBean.setBusniessId(idDateBmnameMap.get("id"));
            imgInfoBean.setContentType("abkWorksCheck");
            imgInfoBean.setFileType("img");
            String uuid = UUID.randomUUID().toString();
            imgUUIDs.add(uuid);
            imgInfoBean.setId(uuid);
            upImgInfoBeanList.add(imgInfoBean);
        }
        oldImgInfo.addAll(upImgInfoBeanList);
        map2.put("sysAttachmentsJson", GsonUtil.bean2Json(oldImgInfo));

        sender.postJson(GsonUtil.map2Json(map2), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                sender.dismissDialog();
                Toast.makeText(EmergencySaveCheckAddActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(response);
                    int state = jsonObject.getInt("state");
                    if (200 == state) {
                        sender.dismissDialog();
                        upImg();
                    } else {
                        Toast.makeText(EmergencySaveCheckAddActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private void upImg() {
        if (selImageList != null && selImageList.size() != 0) {
            List<File> list = new ArrayList<>();
            List<Map<String, String>> params = new ArrayList<>();
            List<Map<String, String>> picparams = new ArrayList<>();
            for (String imgUUID : imgUUIDs) {
                Map<String, String> map = new HashMap<>();
                map.put("id", imgUUID);
                map.put("type", "jiankkElefailrpt");
                params.add(map);
            }
            for (int i = 0; i < selImageList.size(); i++) {
                File file;
                File videofile;
                if (selImageList.get(i).mimeType.equals("image")) {
                    file = new File(selImageList.get(i).path);
                    list.add(file);
                    picparams.add(params.get(i));
                } else {
                    videofile = new File(selImageList.get(i).name);
                    HttpSender sender = new HttpSender(this, baseUrl, Urls.IMG_UP_LOAD);
                    Map<String, String> map = new HashMap<>();
                    map.put("id", imgUUIDs.get(i));
                    map.put("type", "abkWorksCheck");
                    int finalI = i;
                    sender.upImgs2(videofile, map, new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Toast.makeText(EmergencySaveCheckAddActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                            if (finalI == selImageList.size() - 1) {
                                finish();
                            }
                        }
                    });
                }
            }

            LuBanHelper luBanHelper = new LuBanHelper(EmergencySaveCheckAddActivity.this, list, picparams);
            luBanHelper.compression(new StringCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(String response, int id) {
                    Toast.makeText(EmergencySaveCheckAddActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                    finish();
                }
            });
        }
    }
//    private void upImg() {
//        if (selImageList != null && selImageList.size() != 0) {
//            List<File> list = new ArrayList<>();
//            List<ImageItem> images = adapter.getImages();
//            for (ImageItem image : images) {
//                File file = new File(image.path);
//                list.add(file);
//            }
//
//            List<Map<String, String>> params = new ArrayList<>();
//            for (UpImgInfoBean upImgInfoBean : oldImgInfo) {
//                Map<String, String> map = new HashMap<>();
//                map.put("id", upImgInfoBean.getId());
//                map.put("type", "abkWorksCheck");
//                params.add(map);
//            }
//
//            LuBanHelper luBanHelper = new LuBanHelper(EmergencySaveCheckAddActivity.this, list, params);
//            luBanHelper.compression(new StringCallback() {
//                @Override
//                public void onError(Call call, Exception e, int id) {
//                }
//
//                @Override
//                public void onResponse(String response, int id) {
//                    try {
//                        JSONObject jsonObject = new JSONObject(response);
//                        if (jsonObject.getInt("state") == 200) {
//                            finish();
//                            Toast.makeText(EmergencySaveCheckAddActivity.this, "上传成功！", Toast.LENGTH_SHORT).show();
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            });
//        }
//    }


    ArrayList<ImageItem> images = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            switch (resultCode) {
                case ImagePicker.RESULT_CODE_ITEMS:
                    //添加图片返回
                    if (requestCode == REQUEST_CODE_SELECT) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                        if (images != null) {
                            for (int i = 0; i < images.size(); i++) {
                                images.get(i).mimeType = "image";
                            }
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case ImagePicker.RESULT_CODE_BACK:
                    //预览图片返回
                    if (requestCode == REQUEST_CODE_PREVIEW) {
                        images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                        if (images != null) {
                            selImageList.clear();
                            selImageList.addAll(images);
                            adapter.setImages(selImageList);
                        }
                    }
                    break;
                case RESULT_OK:
                    //选择视频返回
                    if (requestCode == REQUEST_CODE_VSELECT) {
                        List<String> videoUrls = Matisse.obtainPathResult(data);
                        Log.e("videoUrls", videoUrls.get(0));
                        videoPath = videoUrls.get(0);
                        MediaMetadataRetriever retr = new MediaMetadataRetriever();
                        retr.setDataSource(videoPath);
                        //获取第一帧图像的bitmap对象
                        Bitmap bitmap = retr.getFrameAtTime();
                        String imgUrl = FileUtil.saveImg2Gallery(this, bitmap,
                                System.currentTimeMillis() / 1000 + "");
                        ImageItem imageItem = new ImageItem();
                        imageItem.path = imgUrl;
                        imageItem.name = videoPath;
                        imageItem.mimeType = "video";
                        selImageList.add(imageItem);
                        adapter.setImages(selImageList);

                    }
                    break;
            }
        }
    }


    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                List<String> names = new ArrayList<>();
                names.add("拍照");
                names.add("相册");
                names.add("视频");
                showDialog(new SelectDialog.SelectDialogListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        switch (position) {
                            case 0: // 直接调起相机
                                /**
                                 * 0.4.7 目前直接调起相机不支持裁剪，如果开启裁剪后不会返回图片，请注意，后续版本会解决
                                 *
                                 * 但是当前直接依赖的版本已经解决，考虑到版本改动很少，所以这次没有上传到远程仓库
                                 *
                                 * 如果实在有所需要，请直接下载源码引用。
                                 */
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent = new Intent(EmergencySaveCheckAddActivity.this, ImageGridActivity.class);
                                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                                startActivityForResult(intent, REQUEST_CODE_SELECT);
                                break;
                            case 1:
                                //打开选择,本次允许选择的数量
                                ImagePicker.getInstance().setSelectLimit(limitSize - selImageList.size());
                                Intent intent1 = new Intent(EmergencySaveCheckAddActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                                startActivityForResult(intent1, REQUEST_CODE_SELECT);
                                break;
                            case 2:
//                                Intent i = new Intent();
//                                i.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
//                                i.setAction(Intent.ACTION_GET_CONTENT);
//                                startActivityForResult(i, REQUEST_CODE_VSELECT);
                                Matisse.from(EmergencySaveCheckAddActivity.this)
                                        .choose(MimeType.ofVideo())
                                        .showSingleMediaType(true)
                                        .theme(R.style.Matisse_Dracula)
                                        .countable(false)
                                        .maxSelectable(1)
                                        .imageEngine(new GlideEngine())
                                        .forResult(REQUEST_CODE_VSELECT);
                                break;
                            default:
                                break;
                        }

                    }
                }, names);
                break;
            default:
                if (adapter.getImages().get(position).mimeType.equals("image")) {
                    //打开预览
                    Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                    intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                    intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                    intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                    startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                } else {
                    Intent intentPreview = new Intent(this, VideoPlayActivity.class);
                    intentPreview.putExtra("videopath", adapter.getImages().get(position).name);
                    startActivity(intentPreview);
                }

                break;
        }
    }

    private SelectDialog showDialog(SelectDialog.SelectDialogListener listener, List<String> names) {
        SelectDialog dialog = new SelectDialog(this, R.style
                .transparentFrameWindowStyle,
                listener, names);
        if (!this.isFinishing()) {
            dialog.show();
        }
        return dialog;
    }

}
